//cart模块
export default {
  //命名空间：让模块具有更高的封装度和复用性
  namespaced: true,
  state: () => ({
    //存储购物车中每个商品的信息对象
    //页面加载时，有数据则显示数据无数据则显示[]
    cart: JSON.parse(uni.getStorageSync('cart') || '[]') 
  }),
  //同步操作
  mutations: {
    //全选/反选
    updateAllCheck (state, newCheck) {
      state.cart.forEach(x => x.goods_state = newCheck)
      //数据更新后，调用saveData,再次存储
      this.commit('cart/saveData')
    },
    
    //添加商品到购物车
    addToCart (state, goods) {
      //判断购物车里是否有相同的商品，如有则数量+1，没有就添加
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      console.log(findResult);
      if(findResult) {
        findResult.goods_count++
      } else {
        state.cart.push(goods)
      }
      // console.log(state.cart);
      //数据更新后，调用saveData,再次存储
      this.commit('cart/saveData')
    },
    //修改商品的选中状态
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_state = goods.goods_state
      }
      //数据更新后，调用saveData,再次存储
      this.commit('cart/saveData')
    },
    //修改购物车商品数量
    updateGoodsCount (state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
      }
      //数据更新后，调用saveData,再次存储
      this.commit('cart/saveData')
    },
    
    //根据id移除购物车商品
    removeGoods (state, goods_id) {
      state.cart = state.cart.filter(x => x.goods_id !== goods_id)
      
      //数据变化，重新存储到本地
      this.commit('cart/saveData')
    },
    //把数据存储到本地，持久化
    saveData (state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    }
  },
  //异步方法
  actions: {},
  // 计算属性
  getters: {
    //统计购物车里商品的数量
    total (state) {
      // let c = 0
      //循环统计商品数量，累加到变量c
      // state.cart.forEach(item => c += item.goods_count)
      // return c
      return state.cart.reduce((total, item) => total += item.goods_count, 0)
    },
    //计算已选中商品的数量
    checkedCount (state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    //计算已选中商品的总价格
    totalPrice (state) {
      //筛选出已选中商品
      //.toFixed(2)保留2位小数
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}